package com.lingkang.sales.config.auth;

import com.alibaba.fastjson.JSONObject;
import com.lingkang.sales.data.domain.SecUser;
import com.lingkang.sales.common.val.HttpCode;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

/**
 * @author linke
 * @date 2020/5/23 18:24
 * @description 用户登录成功时返回给前端的数据
 */
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  @Override
  public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse, Authentication authentication)
      throws IOException, ServletException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", HttpCode.OK);
    jsonObject.put("message", "登录成功！");
    //登录后，返回原访问页面
    RequestCache cache = new HttpSessionRequestCache();
    SavedRequest savedRequest = cache.getRequest(httpServletRequest, httpServletResponse);
    String url = "0";
    try {
      url = savedRequest.getRedirectUrl();
    } catch (Exception e) {
      url = "/";
    }
    jsonObject.put("url", url);
    //重新存储user对象到session
    SecUser securityUser = (SecUser) authentication.getPrincipal();
    System.out.println(securityUser);
    System.out.println(securityUser.getUsername());
    System.out.println(authentication.getAuthorities());
    System.out.println(authentication.getDetails());
    System.out.println(authentication.getPrincipal());
    System.out.println(authentication.getPrincipal());
//    httpServletRequest.getSession().setAttribute("user",oaUserMapper.getUserInfo(securityUser.getUsername()));
    //让浏览器用utf8来解析返回的数据
    httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
    httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
    PrintWriter writer = httpServletResponse.getWriter();
    writer.write(jsonObject.toJSONString());
  }
}
